package com.gitee.cashzhang27.test.boot.redisson.helper;

import cn.hutool.core.date.DateUtil;
import com.gitee.cashzhang27.test.boot.redisson.common.enmu.ServiceCodeEnums;
import com.google.common.base.Strings;
import javax.annotation.Resource;
import lombok.AllArgsConstructor;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/10/20 11:44
 */
@Service
@AllArgsConstructor
public class ServiceCodeHelper {

  @Resource
  private RedissonClient redissonClient;

  public String fetchServiceCode(ServiceCodeEnums serviceCodeEnums) {
    String prefix = serviceCodeEnums.getPrefix();
    String type = DateUtil.format(DateUtil.date(), serviceCodeEnums.getType());
    String pattern = prefix + type;
    RAtomicLong longAdder = redissonClient.getAtomicLong(pattern);
    String code = Strings.padStart(String.valueOf(longAdder.incrementAndGet()), 9, '0');
    return type + code;
  }

}
